#!/bin/bash

# filepath: /d:/projects/flashlight-ui/tools/db_csv_extractor.sh

input_file="$1"
output_dir="${2:-./output}"

if [ -z "$input_file" ]; then
    echo "Error: No input file specified."
    exit 1
fi

mkdir -p "$output_dir"

current_section=""
current_content=""

while IFS= read -r line; do
    if [[ $line =~ START_([a-zA-Z0-9_]+) ]]; then
        if [ -n "$current_section" ]; then
            echo -e "$current_content" > "$output_dir/${current_section}.csv"
        fi
        current_section="${BASH_REMATCH[1]}"
        current_content=""
    elif [[ $line =~ END_([a-zA-Z0-9_]+) ]]; then
        if [ "$current_section" == "${BASH_REMATCH[1]}" ]; then
            echo -e "$current_content" > "$output_dir/${current_section}.csv"
            current_section=""
            current_content=""
        else
            echo "Warning: Mismatched END_ section for $current_section"
        fi
    else
        current_content+="$line\n"
    fi
done < "$input_file"

# Ensure the last section is written if the file does not end with an END_ line
if [ -n "$current_section" ]; then
    echo -e "$current_content" > "$output_dir/${current_section}.csv"
fi
